package com.jewaton.auth.commons.util;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

public class XMLUtil {

    /**
     * @param args
     */
    public static void main(String[] args) {
        XMLConfiguration config = getUTFXmlConfiguration("<xml><test>xml测试</test><empty></empty><null>null</null></xml>");
        System.out.println(config.getString("test"));
        System.out.println(config.getString("empty"));
        System.out.println(config.getString("null"));
        System.out.println(StringUtil.isBlank(config.getString("empty")));
        System.out.println(StringUtil.isBlank(config.getString("null")));
        System.out.println(config.getString("noexist") == null);
        config = getUTFXmlConfiguration(null);
        System.out.println(config.getString("test"));
    }

    /**
     *解析xml字符串，utf-8编码 ,返回的XMLConfiguration是<K,V>对，直接像Map.get(key)取值就行
     */
    public static XMLConfiguration getUTFXmlConfiguration(String source) {
        return getXmlConfiguration(source, "utf-8");
    }
    
    public static XMLConfiguration getXmlConfiguration(String source,String charset) {
        XMLConfiguration config = new XMLConfiguration();
        if (StringUtil.isBlank(source)) 
            return config;
        try {
            config.load(new ByteArrayInputStream(source.getBytes("utf-8")));
        } catch (ConfigurationException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return config;
    }
}
